﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using MiniErp.Entity.JWTs;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace MiniErp.Core.Filters
{

    /// <summary>
    /// 权限拦截器 
    /// </summary>
    public class RoleHandlerFilter : AuthorizationHandler<TokenRequirement>
    {
        /// <summary>
        /// 访问权限鉴别
        /// </summary>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TokenRequirement requirement)
        {
            //IP鉴权
            var httpConnection = context.Resource as DefaultHttpContext;
            if (httpConnection == null)
            {
                context.Fail();
                return Task.CompletedTask;
            }
            switch (httpConnection.Connection.RemoteIpAddress.ToString())
            {
                case "127.0.0.1": break;
                default: context.Fail(); return Task.CompletedTask;
            }
            //身份鉴权--代办：岗位以及部门拦截
            switch (requirement._RightName)
            {
                case "God" when context.User.HasClaim(item => item.Value == "God"): break;
                case "Admin" when context.User.HasClaim(item => item.Value == "Admin" || item.Value == "God"): break;
                case "Root" when context.User.HasClaim(item => item.Value == "Root" || item.Value == "Admin" || item.Value == "God"): break;
                case "Tourist": break;
                default: context.Fail(); return Task.CompletedTask;
            }
            context.Succeed(requirement);
            return Task.CompletedTask;
        }
    }
}
